<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 绑定账号
 *
 * @author      Eden
 * @datetime    2016/12/1 11:40
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Bind_Model extends API_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->driver('cache');
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {
            if (!$this->checkParams($params)) {
                $send['error'] = $this->getError();
                break;
            }

            // 验证码
            if (!$this->checkSms($params)) {
                $send['error'] = '验证码错误';
                break;
            }

            $query = $this->db->get_where('user', array('phone' => $params['phone']));
            $res = $query->row_array();
            if ($res) {
                $data = $this->doPhoneExists($res, $params);
            } else {
                $data = $this->finshBind($params);
            }

            if (!$data) {
                $send['error'] = $this->getError();
            } else {
                $send['state'] = true;
                $send['data'] = $data;
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 当用户已存在的情况
     * @param $user
     * @param $params
     * @return array|bool
     */
    private function doPhoneExists($user, $params)
    {
        $userid = $user['id'];

        $socialDb = clone($this->db);
        $q = $socialDb->get_where('user_social', ['openId' => $params['openId']]);
        $row = $q->row_array();
        if (empty($row)) {
            $this->setError('请先使用第三方账号进行登录');
            return false;
        }

        if (!empty($row['userId'])) {
            $this->setError('已是绑定用户');
            return false;
        }

        $db = clone($this->db);
        $db->where('openId', $params['openId']);
        $db->update('user_social', ['userId' => $userid]);

        $dbProfile = clone($this->db);
        $userPorfile = $dbProfile->get_where('user_profile', ['userId' => $userid]);
        $profile = $userPorfile->row_array();

        $thumbSize = $params['type'] == 'ios' ? 200 : 100;

        if ($db->affected_rows()) {
            return array(
                'userId' => intval($userid),
                'nickName' => $user['nickName'],
                'phone' => $user['phone'],
                'lastTime' => $user['lastTime'],
                'lastIp' => $user['lastIp'],
                'trueName' => $profile['trueName'],
                'avatar' => thumb($profile['avatar'], $thumbSize, $thumbSize),
                'status' => intval($user['status'])
            );
        }

        $this->setError('用户绑定失败');
        return false;
    }

    public function checkSms($params)
    {
        $key = 'API:Member:Bind:' . $params['phone'];
        $cacheData = $this->cache->redis->get($key);
        if ($cacheData) {
            $code = value($cacheData, 'code');
            if ($code == $params['code']) {
                $this->cache->redis->delete($key);
                return true;
            }
        } else {
            $this->output->send(array(
                'state' => false,
                'error' => '验证码已失效'
            ));
        }
        return false;
    }

    /**
     * 完成绑定
     * @param array $params
     * @return bool
     */
    private function finshBind($params = array())
    {
        // 获取会员数据
        $sdb = clone($this->db);
        $query = $sdb->get_where('user_social', array('openId' => $params['openId']));
        $row = $query->row_array();
        if ($row) {
            $nowTime = dateTime();
            $remoteIp = remoteAddr();
            $data = array(
                'nickName' => $row['nickName'],
                'phone' => $params['phone'],
                'lastTime' => $nowTime,
                'lastIp' => $remoteIp,
                'created' => $nowTime,
                'status' => 1
            );

            $userDb = clone($this->db);
            $userDb->trans_start();
            $userDb->insert('user', $data);

            $userId = $userDb->insert_id();
            if (empty($userId)) {
                $this->setError('注册失败');
                return false;
            }

            $userProfile = array(
                'userId' => $userId,
                'avatar' => $row['figureUrl'],
                'trueName' => ''
            );
            $userDb->insert('user_profile', $userProfile);

            $userSDb = clone($this->db);
            $userSDb->where('openId', $params['openId']);
            $userSDb->update('user_social', array('userId' => $userId));
            unset($userSDb);

            $userDb->insert('user_mobile_login', array(
                'userId' => $userId,
                'deviceId' => $params['deviceId'],
                'type' => $params['type'],
                'loginTime' => $nowTime
            ));

            $userDb->trans_complete();
            if ($userDb->trans_status() === FALSE) {
                $this->setError('绑定失败');
                return false;
            }

            return array(
                'userId' => intval($userId),
                'nickName' => $data['nickName'],
                'phone' => $data['phone'],
                'lastTime' => $nowTime,
                'lastIp' => $remoteIp,
                'trueName' => $userProfile['trueName'],
                'avatar' => thumb($userProfile['avatar']),
                'status' => intval($data['status'])
            );
        } else {
            $this->setError('OPENID错误');
            return false;
        }
    }

    /**
     * 检查参数
     * @param $params
     * @return bool
     */
    private function checkParams($params)
    {
        if ($this->input->method(true) !== 'POST') {
            $this->setError('非法请求');
            return false;
        }

        if (empty($params['openId']) || empty($params['phone']) || empty($params['code'])) {
            $this->setError('参数错误');
            return false;
        }

        if (!preg_match('/^1[34578]\d{9}$/', $params['phone'])) {
            $this->setError('手机号格式错误');
            return false;
        }

        if (!preg_match('/^\d{4}$/', $params['code'])) {
            $this->setError('验证码错误');
            return false;
        }
        return true;
    }
}
